package net._7colorlotus.gateway.filters;

import cn.hutool.json.JSONUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义全局过滤器
 */
//@Component
public class AuthFilter implements GlobalFilter, Ordered {

    /**
     * 针对所有路由进行过滤
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String jwtToken = request.getHeaders().getFirst("auth");
        if (StringUtils.isEmpty(jwtToken)) {
            Map retMap = new HashMap() {{
                    put("msg", "没有登录");
            }};
            return response(response, retMap);
        }else if(!"admin".equalsIgnoreCase(jwtToken)){
            Map retMap = new HashMap() {{
                put("msg", "token error");
            }};
            return response(response, retMap);
        }else {
            return chain.filter(exchange);
        }
    }


    private Mono<Void> response(ServerHttpResponse response, Object msg) {
        response.getHeaders().add("ContentType", "application/json;charset=UTF-8");
        String resJson = JSONUtil.toJsonStr(msg);
        DataBuffer wrap = response.bufferFactory().wrap(resJson.getBytes());
        return response.writeWith(Flux.just(wrap));
    }

    /**
     * 数字越小，越先执行
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
